package com.agent;

import com.interceptor.GatewayDelegateLogic;
import com.interceptor.SessionAuthDelegateLogic;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;

import java.lang.instrument.Instrumentation;

public class T_06_DelegateSessionAuthAgent {

    public static void premain(String args, Instrumentation inst) {
        System.out.println("agent=========T_06_DelegateSessionAuthAgent.premain()");
        install(inst);
    }

    public static void agentmain(String args, Instrumentation inst) {
        System.out.println("agent=========T_06_DelegateSessionAuthAgent.agentmain");
        install(inst);
    }

    private static void install(Instrumentation inst) {
        new AgentBuilder.Default()
                .type(ElementMatchers.named("com.gillion.dip.auth.session.SessionAuth"))
                .transform((builder, td, cl, m) ->
                        builder.method(ElementMatchers.named("readUser")
                                        .and(ElementMatchers.isStatic())
                                )
                                // 1. 整个方法委派给 MyLogic 里的静态方法
                                .intercept(MethodDelegation.to(SessionAuthDelegateLogic.class))
                )
                .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
                .installOn(inst);
    }
}